package org.jeik.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jeik.beackBeans.AppSessionBean;

/**
 * Servlet Filter implementation class SecurityFilter
 * 
 * 
 * @author AAsha
 */
public class SecurityFilter implements Filter {

    /**
     * Default constructor. 
     */
    public SecurityFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
	      HttpServletResponse resp = (HttpServletResponse) response;
	      HttpServletRequest req = (HttpServletRequest) request;
	      String servletPath = req.getRequestURI();

	      // Allow access to login functionality.
	      if (servletPath.endsWith("/admin/login.xhtml")  
	    		  || servletPath.endsWith(".css")
	    		  || servletPath.endsWith(".js")
	    		  || servletPath.endsWith(".pdf")
	    		  || servletPath.endsWith(".png")
	    		  || servletPath.endsWith(".jpg")) {
	         chain.doFilter(req, resp);
	         return;
	      }
	      
	      HttpSession session = req.getSession();
	      Object appSessionBean = session.getAttribute("appSessionBean");
	      
	      if (appSessionBean != null && ((AppSessionBean)appSessionBean).getUser() != null) {
	         chain.doFilter(req, resp);
	         return;
	      }else{
	    	  resp.sendRedirect("/JEIK/faces/page/admin/login.xhtml");
	      }
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
